package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.LocalTime;

@Component
@Slf4j
@Aspect
public class AutoFillAspect {
    /**
     * 切入点
     */
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void AutoFillPointCut(){}

    @Before("AutoFillPointCut()")
    public void doAutoFill(JoinPoint joinPoint){
        log.info("执行自动填充的逻辑...");

        //获取签名
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        OperationType operationType = signature.getMethod().getAnnotation(AutoFill.class).value();//sql类型

        log.info("当前操作类型为：{}",operationType);

        //准备要导入的数据
        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();

        //获得要公共字段赋值的对象
        Object object = joinPoint.getArgs()[0];
        //判断是否为空
        if (object==null){
            return;
        }

        //根据不同赋值类型，通过反射进行赋值，即用参数的类调用类里的方法去设置值
        switch (operationType){
            case INSERT:
                try {
                    object.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME,LocalDateTime.class)
                            .invoke(object,now);
                    object.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class)
                            .invoke(object,now);
                    object.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER,Long.class)
                            .invoke(object,currentId);
                    object.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER,Long.class)
                            .invoke(object,currentId);

                } catch (Exception e) {
                    log.error("公共字段赋值失败",e);
                }
            case UPDATE:
                try {
                    object.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class)
                            .invoke(object,now);
                    object.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER,Long.class)
                            .invoke(object,currentId);
                } catch (Exception e) {
                    log.error("公共字段赋值失败",e);
                }
        }



    }
}
